package cn.shengchao.ycbdc.domain.token;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.shengchao.ycbdc.domain.result.UserInfoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.continew.starter.core.exception.BaseException;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @program: examstarapi
 * @description: 忆成背单词第三方token
 * @author: Xiong weiqiang
 * @create: 2025-05-21 14:33
 */
@Component
public class YcBdcTokenUtil {
    private static final String AUTH_REQ_URL ="/wechat/englishWxUser/loginOrRegisterByPhone";
    private static final String USERINFO_REQ_URL ="/wechat/englishWxUser/getUserInfo";
    private static final String ORDER_ADD_DAY_REQ_URL ="/wechat/englishWxUser/channelMembers";
    private static final String TOKEN_VALUE_KEY = "ycbdc_token_value:";
    private static final Integer SUCCESS_CODE = 2000;

    @Value("${third.ycbdc.serverUrl:http://zdd368a5.natappfree.cc}")
    private String serverUrl;
    @Value("${third.ycbdc.orgCode:YC}")
    private String orgCode;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取缓存token
     * @param mobile
     * @return
     */
    private String getRedisKey(String mobile){
        return TOKEN_VALUE_KEY+mobile;
    }
    /**
     * 获取忆成背单词第三方token
     * @return
     */
    public String getRedisToken(String mobile,String nickName) {
        String tokenResp=null;
        String key=getRedisKey(mobile);
        if (stringRedisTemplate.hasKey(key)) {
            tokenResp = stringRedisTemplate.opsForValue().get(key);
            return tokenResp;
        }else {
            tokenResp = reqYcTokenResponseStr(mobile,nickName);
        }
        return tokenResp;
    }
    /**
     * 获取token
     * @param mobile
     * @param nickName
     * @return
     */
    private String reqYcTokenResponseStr(String mobile,String nickName){
        Map<String,Object> params=new HashMap<>();

        Long timestamp= System.currentTimeMillis();
        String token="mobile="+mobile+"&orgCode="+orgCode+"&timestamp="+timestamp;
        String tokenMd5= DigestUtil.md5Hex(token);
        params.put("token",tokenMd5);
        params.put("orgCode",orgCode);
        params.put("mobile",mobile);
        params.put("timestamp",timestamp);
        params.put("nickName",nickName);
        String url=serverUrl+AUTH_REQ_URL;
        String resultStr=HttpUtil.post(url, JSONUtil.toJsonStr(params));
        if (JSONUtil.isTypeJSON(resultStr)&&SUCCESS_CODE.equals(new JSONObject(resultStr).getInt("code"))){
            String key=getRedisKey(mobile);
            stringRedisTemplate.opsForValue().set(key,resultStr);
            //缓存token，设置过期时间（1天1换，第三方是30天，但也不知道它哪天过期，每天请求一次）
            stringRedisTemplate.expire(key,1, TimeUnit.DAYS);
            return resultStr;
        }else {
            return null;
        }
    }
    /**
     * 获取token
     * @param mobile
     * @param nickName
     * @return
     */
    private JSONObject getTokenJson(String mobile,String nickName){
        String tokenResp=getRedisToken(mobile,nickName);
        if (StrUtil.isNotBlank(tokenResp)){
            return new JSONObject(tokenResp).getJSONObject("data");
        }else {
            throw new BaseException("请求忆成服务失败，请检查检查token");
        }
    }
    /**
     * 获取用户信息
     * @param mobile
     * @param nickName
     * @return
     */
    public UserInfoResult getUserInfo(String mobile, String nickName){

        String userInfoUrl=serverUrl+USERINFO_REQ_URL;
        if (null==mobile||mobile.length()<11){
            throw new BaseException("手机号不合法");
        }else {
            JSONObject tokenObject=getTokenJson(mobile,nickName);
            String tokenValue=tokenObject.getStr("tokenValue");
            String tokenName=tokenObject.getStr("tokenName");
            HttpRequest request=HttpUtil.createGet(userInfoUrl);
            request.header(tokenName,tokenValue);
            String userInfo= request.execute().body();
            System.out.println("用户手机:"+mobile+",用户信息返回response:"+userInfo);
            if (JSONUtil.isTypeJSON(userInfo)&&SUCCESS_CODE.equals(new JSONObject(userInfo).getInt("code"))){
                return JSONUtil.toBean(new JSONObject(userInfo).getStr("data"), UserInfoResult.class);
            }else{
                //重复1次请求
                String tokenStr=reqYcTokenResponseStr( mobile,  nickName);
                if (StrUtil.isNotBlank(tokenStr)){
                    JSONObject tokenObject1=new JSONObject(tokenStr).getJSONObject("data");
                    String tokenValue1=tokenObject1.getStr("tokenValue");
                    String tokenName1=tokenObject1.getStr("tokenName");
                    HttpRequest request1=HttpUtil.createGet(userInfoUrl);
                    request1.header(tokenName1,tokenValue1);
                    String userInfo1= request1.execute().body();
                    System.out.println("用户手机1:"+mobile+",用户信息1返回response:"+userInfo1);
                    if (JSONUtil.isTypeJSON(userInfo1)&&SUCCESS_CODE.equals(new JSONObject(userInfo1).getInt("code"))){
                        return JSONUtil.toBean(new JSONObject(userInfo1).getStr("data"), UserInfoResult.class);
                    }
                }
            }
            return null;
        }
    }

    /**
     * 订单购买后增加天数
     * @param mobile
     * @param nickName
     * @return
     */
    public Boolean addOrderDays(String mobile,String nickName,Integer count){
        JSONObject tokenObject=getTokenJson(mobile,nickName);
        String tokenValue=tokenObject.getStr("tokenValue");
        String tokenName=tokenObject.getStr("tokenName");
        String userOrderAddDayUrl=serverUrl+ORDER_ADD_DAY_REQ_URL+"?count="+count;
        HttpRequest orderRequest=HttpUtil.createGet(userOrderAddDayUrl);
        orderRequest.header(tokenName,tokenValue);
        String orderResult= orderRequest.execute().body();
        System.out.println("用户手机:"+mobile+",用户订单调用后response:"+orderResult);
        return JSONUtil.isTypeJSON(orderResult)&&SUCCESS_CODE.equals(new JSONObject(orderResult).getInt("code"));

    }
    public static void main(String[] args){
        String mobile="13111111111";
        String nickname="13111111111";
        String serverUrl="https://api-cloud.yixuewang.cn";
        String orgCode="YC";
        Long timestamp= System.currentTimeMillis();
        String token="mobile="+mobile+"&orgCode="+orgCode+"&timestamp="+timestamp;
        Map<String,Object> params=new HashMap<>();
        String tokenMd5= DigestUtil.md5Hex(token);
        params.put("token",tokenMd5);
        params.put("orgCode",orgCode);
        params.put("mobile",mobile);
        params.put("timestamp",timestamp);
        params.put("nickName",nickname);
        String url=serverUrl+AUTH_REQ_URL;
        String resultStr=HttpUtil.post(url, JSONUtil.toJsonStr(params));

        System.out.println("请求地址:"+url);
        System.out.println("token原值:"+ token);
        System.out.println("参数值:"+ JSONUtil.toJsonStr(params));
        System.out.println("返回值:"+resultStr);
        String tokenValue=new JSONObject(resultStr).getJSONObject("data").getStr("tokenValue");
        String tokenName=new JSONObject(resultStr).getJSONObject("data").getStr("tokenName");
        String userInfoUrl=serverUrl+USERINFO_REQ_URL;
        HttpRequest request=HttpUtil.createGet(userInfoUrl);
        request.header(tokenName,tokenValue);
        String userInfo= request.execute().body();

        System.out.println("请求地址:"+userInfoUrl);
        System.out.println("header tokenName:"+ tokenName);
        System.out.println("header tokenValue:"+ tokenValue);
        System.out.println("返回值:"+userInfo);

        String userOrderAddDayUrl=serverUrl+ORDER_ADD_DAY_REQ_URL+"?count="+30;
        HttpRequest orderRequest=HttpUtil.createGet(userOrderAddDayUrl);
        orderRequest.header(tokenName,tokenValue);
        String orderResult= orderRequest.execute().body();

//        返回值:{"code":2000,"data":null,"msg":"成功","requestId":"17006634935900608"}
        System.out.println("请求地址:"+userOrderAddDayUrl);
        System.out.println("header tokenName:"+ tokenName);
        System.out.println("header tokenValue:"+ tokenValue);
        System.out.println("返回值:"+orderResult);
        String userInfo1= request.execute().body();

        System.out.println("请求地址:"+userInfoUrl);
        System.out.println("header tokenName:"+ tokenName);
        System.out.println("header tokenValue:"+ tokenValue);
        System.out.println("返回值:"+userInfo1);

    }
}